package com.itstyle.quartz.job;

import com.alibaba.fastjson.JSON;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class MonitorStateJob implements Job,Serializable {

    private static final long serialVersionUID = -1702240244561581996L;

    private static final Logger log = LoggerFactory.getLogger(MonitorStateJob.class);

    private StdSchedulerFactory schedulerFactory= new StdSchedulerFactory();

    @Autowired
    @Qualifier("Scheduler")
    private Scheduler scheduler;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        try {
//            scheduler = schedulerFactory.getScheduler();
//            GroupMatcher<TriggerKey> var1= new GroupMatcher<TriggerKey>()
//            scheduler.getTriggerKeys()
//            scheduler.getTriggerState();

//            log.info("scheduler.getJobGroupNames "+JSON.toJSONString(scheduler.getJobGroupNames()));
            for (String groupName : scheduler.getJobGroupNames()) {

                for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {

                    String jobName = jobKey.getName();
                    String jobGroup = jobKey.getGroup();

                    //get job's trigger
                    List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);

                    Date nextFireTime = triggers.get(0).getNextFireTime();
                    for (Trigger trigger :triggers){

                        if ("CheckJob".equals(jobName))
                        log.info("[jobName] : " + jobName + " [groupName] : "
                                + jobGroup + " - " + nextFireTime+" State "+scheduler.getTriggerState(trigger.getKey()));

                    }

                }

            }


        }catch (SchedulerException e){
            e.printStackTrace();
        }


    }
}
